<?php 

	session_start();

	// check for login
	if(!isset($_SESSION['atbat']) && !isset($_COOKIE['remember_atbat'])) {

		// no login, move to index page
		header("Location: http://localhost/atbat/html/");

	}

	// connect to db
	require_once '../db/db.php';
	
	// load helper functions
	require_once 'include/functions.php';

	// get user id
	$sql = "SELECT user_id FROM users WHERE MD5(username) IN ('";
	$sql .= ((isset($_SESSION['atbat'])) ? $_SESSION['atbat'] : '') . "', '";
	$sql .= ((isset($_COOKIE['remember_atbat'])) ? $_COOKIE['remember_atbat'] : '') . "')";

	$id = $db->query($sql)->fetchAll();
	$user_id = $id[0]['user_id'];
	
	// process game creation
	if(isset($_POST['create_game'])) {
		
		// sanitize and validate data
		$error = false;
		
		// game date
		if(isset($_POST['date']) && $_POST['date'] != '') {
			
			if(filter_var($_POST['date'], FILTER_CALLBACK, array("options" => "is_date"))) {
				
				$date = date('Y-m-d', strtotime($_POST['date']));	
				
			}else{
				
				$error = true;
				$message[] = '<p class="error">Please enter a valid date (MM/DD/YYYY).</p>';
				
			}
			
		}else{
			
			$error = true;
			$message[] = '<p class="error">Please enter a date for this game.</p>';
			
		}
		
		// start time
		if(isset($_POST['start_time']) && $_POST['start_time'] != '') {
			
			if(filter_var($_POST['start_time'], FILTER_CALLBACK, array("options" => "is_time"))) {
				
				$start_time = $_POST['start_time'];
				
			}else{
				
				$error = true;
				$message[] = '<p class="Please enter a valid start time (HH:MM).</p>';
				
			}
			
		}else{
			
			$error = true;
			$message[] = '<p class="error">Please enter a start time for this game.</p>';
			
		}
		
		// away team
		if(isset($_POST['away_team']) && $_POST['away_team'] != '') {
			
			if(filter_var($_POST['away_team'], FILTER_VALIDATE_INT)) {
				
				$away_team = filter_var($_POST['away_team'], FILTER_SANITIZE_NUMBER_INT);
				
			}else{
				
				$error = true;
				$message[] = '<p class="error">Invalid Team ID specified.</p>';
				
			}
			
		}else{
			
			$error = true;
			$message[] = '<p class="error">Please choose an Away Team.</p>';
			
		}
		
		// home team
		if(isset($_POST['home_team']) && $_POST['home_team'] != '') {
			
			if(filter_var($_POST['home_team'], FILTER_VALIDATE_INT)) {
				
				$home_team = filter_var($_POST['home_team'], FILTER_SANITIZE_NUMBER_INT);
				
			}else{
				
				$error = true;
				$message[] = '<p class="error">Invalid Team ID specified.</p>';
				
			}
			
		}else{
			
			$error = true;
			$message[] = '<p class="error">Please choose an Home Team.</p>';
			
		}
		
		// attendance -- optional
		if(isset($_POST['attendance']) && $_POST['attendance'] != '') {
			
			$opts = array('min_range' => 0, 'max_range' => 68000);
			if(filter_var($_POST['attendance'], FILTER_VALIDATE_INT, $opts)) {
				
				$attendance = filter_var($_POST['attendance'], FILTER_SANITIZE_NUMBER_INT);
				
			}else{
				
				$error = true;
				$message[] = '<p class="error">Invalid number format for attendance.</p>';
				
			}
			
		}else{
			
			$attendance = 0;	
			
		}
		
		// enter data into db
		// transaction to populate both the games and game_details tables
		try {
			
			$db->beginTransaction();
			$db->exec("INSERT INTO games (user_id, date, start_time, away_team, home_team) VALUES (" . $user_id . ", '" . $date . "', '" . $start_time . "', " . $away_team . ", " . $home_team . ")");
			$g_id = $db->lastInsertId();
			$db->exec("INSERT INTO game_details (game_id, user_id, away_team, home_team, game_date, attendance) VALUES (" . $g_id . ", " . $user_id . ", " . $away_team . ", " . $home_team . ", '" . $date . "', " . $attendance . ")");
			$db->commit();
			$message[] = '<p class="success">Successfully created your game. You will be redirected in 3 seconds.</p>';
			
			sleep(3);
			
			// step two, choose roster for each team
			header("Location: http://localhost/atbat/html/choose-roster/" . $g_id);
			
		} catch(PDOException $e) {
			
			$db->rollBack();
			$message[] = '<p class="error">Failed to create new game.</p>';
			$message[] = '<p class="notice">' . $e->getMessage() . '</p>';
			$error = true;	
			
		}
		
	}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <base href="http://localhost/atbat/html/" />
	<meta charset="utf-8">
	<title>AtBat :: Score a New Game</title>
	<meta name="description" content="">
	<meta name="author" content="Sean Mullin, http://parametercontraption.com">
	<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">
	<link rel="shortcut icon" href="images/design/favicon.ico">
	<link rel="apple-touch-icon" href="images/design/apple-touch-icon.png">
	<link rel="stylesheet" href="css/screen.css"><link rel="stylesheet" media="all" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/themes/base/jquery-ui.css">
    <script src="js/modernizr-1.5.min.js"></script>
</head>
<body>
	<?php require_once 'include/header.html'; ?>
    <section id="content">
        <h1>Start a New Game</h1>
    	<form id="gameForm" method="post" action="new-game">
        	<fieldset>
            	<legend>Game Details</legend>
                <?php if(isset($message)) foreach($message as $m) print $m; ?>
                <p><label for="date">Game Date:</label><input type="date" name="date" id="date" placeholder="MM/DD/YYYY" required /></p>
                <p><label for="start_time">Start Time:</label><input type="time" name="start_time" id="start_time" placeholder="HH:MM" required /></p>
                <p>
                	<label for="away_team">Away Team:</label>
                    <select name="away_team" id="away_team" class="teamSelect" required>
                    	<option value="0">Choose One</option>
                    	<?php

							foreach($db->query("SELECT team_id, city, name FROM teams WHERE user_id IN (0, " . $user_id . ")") as $t) {

								print '<option value="' . $t['team_id'] . '">' . $t['city'] . ' ' . $t['name'] . '</option>';

							}

						?>
                    	<option value="">Create a New Team</option>
                    </select>
                </p>
                <p>
                	<label for="home_team">Home Team:</label>
                    <select name="home_team" id="home_team" class="teamSelect" required>
                    	<option value="0">Choose One</option>
                    	<?php

							foreach($db->query("SELECT team_id, city, name FROM teams WHERE user_id IN (0, " . $user_id . ")") as $t) {

								print '<option value="' . $t['team_id'] . '">' . $t['city'] . ' ' . $t['name'] . '</option>';

							}

						?>
                    	<option value="">Create a New Team</option>
                    </select>
                </p>
                <p><label for="attendance">Attendance:</label><input type="number" name="attendance" id="attendance" min="0" max="68000" /></p>
                <input type="submit" name="create_game" id="create_game" value="Continue to Step Two" />
            </fieldset>
        </form>
    </section>
    <?php require_once 'include/footer.html'; ?>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/jquery-ui.min.js"></script>
    <script>
    	$(document).ready(function() {	
			// check for native date picker, default to jQuery UI if not
			if(!Modernizr.inputtypes.date) {
				$( "#date" ).datepicker({
					changeMonth: true,
					changeYear: true,
					dateFormat: 'mm/dd/yy',
					yearRange: '1900:2011'
				});
			}
			
			// TODO: make this work with file uploads		
			$(".teamSelect").change(function() { // listen for change on team input
				// show new team form
				if($(this).val() == '') {
					$("#dialogTeam").dialog("open");
				}
			});
			
			// new team dialog
			$("#dialogTeam").dialog({
				autoOpen: false,
				width: 648,
				modal: true,
				draggable: false,
				resizable: false,
				buttons: {
					"Create Team": function() {
						$.post(
							"create-team.php",
							{
								team_city: $("#team_city").val(),
								team_name: $("#team_name").val(),
								division: $("#division").val(),
								league: $("#league").val(),
								url: $("#url").val(),
								createTeam: $("#createTeam").val()
							},
							function(data) {
								$(".error").remove();
								$(".success").remove();
								$(".notice").remove();
								$("#dialogTeam").prepend(data);
								if($(data).hasClass('success')) {
									// set value of team select input
									var select_id = $(data).attr("rel");
									var select_title = $(data).attr("title");
									$(".teamSelect").append('<option value="' + select_id + '" selected>' + select_title + '</option>');

									// close window after 2.5 seconds on success
									setTimeout(function() { $("#dialogTeam").dialog("close"); }, 2500);
								}
							}
						);
					},
					Cancel: function() { $(this).dialog("close"); }
				}
			});
		});
    </script>
    <fieldset id="dialogTeam" title="Create a New Team">
    	<p><label for="team_city">Team City:</label><input type="text" name="team_city" id="team_city" required /></p>
        <p><label for="team_name">Team Name:</label><input type="text" name="team_name" id="team_name" required /></p>
        <p><label for="division">Division:</label><select name="division" id="division"><?php createSelect('division'); ?></select></p>
        <p><label for="league">League:</label><select name="league" id="league"><?php createSelect('league'); ?></select></p>
        <p><label for="url">Team URL:</label><input type="url" name="url" id="url" placeholder="http://www.example.com" /></p>
        <input type="hidden" name="createTeam" value="1" id="createTeam" />
    </fieldset>
</body>
</html>